package org.wjw;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.wjw.model.Student;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/jackson")
public class JacksonServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 设置请求与响应的字符编码
        req.setCharacterEncoding("utf-8");
        resp.setContentType("application/json; charset=utf-8");

        // 通过ObjectMapper类的对象，可以实现JSON字符串 <==> JAVA 对象的转换
        ObjectMapper objectMapper = new ObjectMapper();
        // 从流中读到源数据，转换成JAVA对象
        Student student = objectMapper.readValue(req.getInputStream(), Student.class);
        // 对获取到的对象进行操作
        student.setStudentId(student.getStudentId() + 100);
        student.setStudentName(student.getStudentName() + "_修改");

        // 返回响应
        // 把修改后的student对象转换成JSON字符串
        String json = objectMapper.writeValueAsString(student);
        System.out.println(json);
        resp.getWriter().write(json);

    }
}
